package org.jeecg.modules.supplierEvaluation.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.bid.entity.Bid;
import org.jeecg.modules.bid.service.IBidService;
import org.jeecg.modules.purchase.service.IPurchasePlanService;
import org.jeecg.modules.supplier.entity.Supplier;
import org.jeecg.modules.supplier.service.ISupplierService;
import org.jeecg.modules.supplierEvaluation.Vo.SupplierEvaluationStatsVo;
import org.jeecg.modules.supplierEvaluation.Vo.SupplierEvaluationVo;
import org.jeecg.modules.supplierEvaluation.dto.SupplierEvaQueryRequest;
import org.jeecg.modules.supplierEvaluation.entity.SupplierEvaluation;
import org.jeecg.modules.supplierEvaluation.service.ISupplierEvaluationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Api(tags = "供应商评价77")
@RestController
@RequestMapping("procurement/supplier/evaluation")
@Slf4j
public class SupplierEvaluationController extends JeecgController<SupplierEvaluation,ISupplierEvaluationService> {
    @Autowired
    private   ISupplierEvaluationService evaluationService;
    @Autowired
    private ISupplierService supplierService;

    @Autowired
    private IPurchasePlanService purchasePlanService;
    @Autowired
    private IBidService bidService;



    @AutoLog(value = "供应商评价-添加评论")
    @ApiOperation("供应商评价-添加评论")
    @PostMapping("/add")
    public Result<?> add(@RequestBody SupplierEvaluationVo evaluationVo) {
        // 参数校验
        if (evaluationVo == null) {
            log.warn("【供应商评价】添加评论失败: 请求参数为空");
            return Result.error("请求参数不能为空");
        }

        if (StringUtils.isEmpty(evaluationVo.getSupplierId())) {
            log.warn("【供应商评价】添加评论失败: 供应商ID为空");
            return Result.error("供应商ID不能为空");
        }

        if (StringUtils.isEmpty(evaluationVo.getProjectName())) {
            log.warn("【供应商评价】添加评论失败: 项目名称为空");
            return Result.error("项目名称不能为空");
        }
        boolean isExistPurchasePlan = purchasePlanService.isExistPurchasePlan(evaluationVo.getPurchaseId());
        if (!isExistPurchasePlan) {
            log.warn("【供应商评价】添加失败: 采购方案不存在，ID={}", evaluationVo.getPurchaseId());
            return Result.error("采购方案不存在");
        }
        SupplierEvaluation evaluation = new SupplierEvaluation();
        // 将Vo转换为实体
        BeanUtils.copyProperties(evaluationVo, evaluation);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//         设置创建人信息
        String username = sysUser.getUsername();
        evaluation.setCreateBy(username);
        evaluation.setCreateTime(new Date());
        evaluation.setUpdateBy(username);
        evaluation.setUpdateTime(new Date());

        //添加到数据库
        boolean result = evaluationService.add(evaluation);
        if (!result) {
            log.error("【供应商评价】添加评论失败: 保存评价数据失败");
            throw new RuntimeException("添加评论失败！");
        }
        // 计算平均分并更新供应商
        try {
            BigDecimal averageScore = evaluationService.calculateAverageScore(evaluationVo.getSupplierId());
            Supplier supplier = supplierService.getById(evaluationVo.getSupplierId());
            if (supplier == null) {
                log.error("【供应商评价】添加评论失败: 供应商不存在，ID={}", evaluationVo.getSupplierId());
                return Result.error("供应商不存在");
            }

            supplier.setTotalScore(averageScore);
            supplier.setAvgScore(averageScore);
            supplier.setLatestScoreTime(new Date());
            supplierService.updateById(supplier);
        } catch (Exception e) {
            log.error("【供应商评价】更新供应商评分失败: 供应商ID={}", evaluationVo.getSupplierId(), e);
            // 不影响评论添加成功，只记录日志
        }

        return Result.OK("添加评论成功！");
    }

    @ApiOperation("供应商评价-根据评价ID获取评价详细")
    @GetMapping("/detail/{id}")
    public Result<?> detail(@PathVariable String id) {
        // 添加ID校验
        if (StringUtils.isEmpty(id)) {
            log.warn("【供应商评价】获取详情失败: 评价ID为空");
            return Result.error("评价ID不能为空");
        }
        try {
            SupplierEvaluation evaluation = evaluationService.getById(id);
            if (evaluation == null) {
                log.warn("【供应商评价】获取详情失败: 评价ID不存在，ID={}", id);
                return Result.error("不存在该供应商评价");
            }
            return Result.OK(evaluation);
        }catch (Exception e){
            log.error("【供应商评价】获取详情失败: 评价ID不存在，ID={}", id);
            return Result.error("获取评价详细失败");
        }

    }

    @ApiOperation("供应商评价-分页查询评价记录")
    @GetMapping("/list")
    public Result<IPage<SupplierEvaluation>> list(
            @RequestParam(defaultValue = "1") Integer pageNo,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        // 添加分页参数校验
        if (pageNo == null || pageNo < 1) {
            log.warn("【供应商评价】分页查询失败: 页码不合法，页码={}", pageNo);
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1 || pageSize > 100) {
            log.warn("【供应商评价】分页查询失败: 每页数量不合法，数量={}", pageSize);
            pageSize = 10;
        }

        Page<SupplierEvaluation> page = new Page<>(pageNo, pageSize);
        IPage<SupplierEvaluation> resultPage = evaluationService.page(page);
        if (resultPage.getTotal() == 0) {
            return Result.OK("未查询到评价记录", resultPage);
        }
        return Result.OK(resultPage);
    }

    @ApiOperation("供应商评价-根据供应商ID查询评价")
    @GetMapping("/history/{supplierId}")
    public Result<List<SupplierEvaluation>> history(@PathVariable String supplierId) {
        // 添加供应商ID校验
        if (StringUtils.isEmpty(supplierId)) {
            log.warn("【供应商评价】查询历史失败: 供应商ID为空");
            throw new RuntimeException("供应商ID不能为空");
        }

        List<SupplierEvaluation> evaluations = evaluationService.getHistoryBySupplierId(supplierId);
        if (evaluations.isEmpty()) {
            log.info("【供应商评价】查询历史: 供应商ID={} 无评价记录", supplierId);
            return Result.OK("该供应商无评价记录", evaluations);
        }
        return Result.OK(evaluations);
    }

    /**
     * 根据供应商ID查询供应商评价表总分的平均分
     *
     * @param supplierId 供应商ID
     * @return 平均分
     */
    @ApiOperation(value = "供应商评价表-根据供应商ID查询平均分", notes = "供应商评价表-根据供应商ID查询平均分")
    @GetMapping(value = "/averageBysupplier")
    public Result<?> averageBysupplier(@RequestParam(name = "supplierId") String supplierId) {
        // 添加供应商ID校验
        if (StringUtils.isEmpty(supplierId)) {
            log.warn("【供应商评价】查询平均分失败: 供应商ID为空");
            return Result.error("供应商ID不能为空");
        }
        BigDecimal averageScore = evaluationService.calculateAverageScore(supplierId);
        if (averageScore.equals(BigDecimal.ZERO)){
            log.info("【供应商评价】查询平均分: 供应商ID={} 无评价记录", supplierId);
            return Result.OK("该供应商无评价记录", averageScore);
        }
        return Result.OK(averageScore);
    }
    @ApiOperation("供应商评价-根据供应商ID查询参与的项目列表")
    @GetMapping("/projects/{supplierId}")
    public Result<Object> getProjectsBySupplierId(@PathVariable String supplierId) {
        // 添加供应商ID校验
        if (StringUtils.isEmpty(supplierId)) {
            log.warn("【供应商评价】查询项目列表失败: 供应商ID为空");
            return Result.error("供应商ID不能为空");
        }

        try {
            // 根据供应商ID和bidStatus查询对应的项目信息
            QueryWrapper<Bid> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("supplier_id", supplierId); // 确保查询条件正确
            queryWrapper.eq("bid_status", 4); // bidStatus必须等于4

            List<Bid> bidList = bidService.list(queryWrapper);

            return Result.OK(bidList);
        } catch (Exception e) {
            log.error("【供应商评价】查询项目列表失败: 供应商ID={}, 异常信息={}", supplierId, e.getMessage());
            return Result.error("查询项目列表失败: " + e.getMessage());
        }
    }


    @ApiOperation("供应商评价-模糊查询")
    @GetMapping("/getSupplierEvaBysearch")
    public Result<?> getSupplierEvaBysearch(SupplierEvaQueryRequest  queryRequest){
        // 如果queryRequest为null，创建默认实例
        if (queryRequest == null) {
            queryRequest = new SupplierEvaQueryRequest();
        }
        // 设置默认分页参数
        if (queryRequest.getPageNum() == null || queryRequest.getPageNum() <= 0) {
            queryRequest.setPageNum(1);
        }
        if (queryRequest.getPageSize() == null || queryRequest.getPageSize() <= 0) {
            queryRequest.setPageSize(10);
        }
        // 创建查询条件
        Page<SupplierEvaluation> page = new Page<>(queryRequest.getPageNum(), queryRequest.getPageSize());
        QueryWrapper<SupplierEvaluation> queryWrapper = new QueryWrapper<>();
        //使用前端传入的供应商名称，到供应商表中查询可能的supplierId
        if(queryRequest.getSupplierName()!=null && !queryRequest.getSupplierName().isEmpty()){
            List<String>  supplierIds =  supplierService.getSupplierIdByName(queryRequest.getSupplierName());
            queryWrapper.in("supplier_id", supplierIds);
        }
        // 按创建时间倒序排列
        queryWrapper.orderByDesc("create_time");
        try {
            Page<SupplierEvaluation> EvaluationPageList = evaluationService.page(page, queryWrapper);
            if (page.getTotal() == 0){
                return Result.OK("未查询到符合条件的评价记录", EvaluationPageList);
            }
            return Result.OK(EvaluationPageList);
        }catch (Exception e) {
            log.error("查询评价记录失败", e);
            return Result.error("查询评价记录失败：" + e.getMessage());
        }

    }

    /**
     * 根据supplierId查询供应商评价记录，按purchaseId分组并按创建时间排序
     * @param supplierId 供应商ID
     * @return 分组后的评价记录
     */
    @AutoLog(value = "供应商评价-按项目分组查询")
    @ApiOperation("供应商评价-按项目分组查询")
    @GetMapping(value = "/getBySupplierIdGroupByPurchaseId")
    public Result<?> getBySupplierIdGroupByPurchaseId(@RequestParam(name = "supplierId", required = true) String supplierId) {
        try {
            // 参数校验
            if (StringUtils.isEmpty(supplierId)) {
                return Result.error("供应商ID不能为空");
            }

            // 调用服务层方法
            java.util.LinkedHashMap<String, List<SupplierEvaluationVo>> groupedEvaluations =
                    evaluationService.getBySupplierIdGroupByPurchaseId(supplierId);

            if (groupedEvaluations.isEmpty()) {
                return Result.OK("未查询到评价记录", groupedEvaluations);
            }

            return Result.OK("查询成功", groupedEvaluations);
        } catch (Exception e) {
            log.error("按项目分组查询评价记录失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据供应商ID查询供应商评价统计信息
     * @param supplierId 供应商ID
     * @return 包含平均评分、组数、完工率、达标率的统计信息
     */
    @AutoLog(value = "供应商评价-统计信息")
    @ApiOperation("供应商评价-统计信息")
    @GetMapping(value = "/getSupplierEvaluationStats")
    public Result<?> getSupplierEvaluationStats(@RequestParam(name = "supplierId", required = true) String supplierId) {
        try {
            // 参数校验
            if (StringUtils.isEmpty(supplierId)) {
                log.warn("【供应商评价】统计信息查询失败: 供应商ID为空");
                return Result.error("供应商ID不能为空");
            }

            // 调用服务层方法
            SupplierEvaluationStatsVo stats = evaluationService.getSupplierEvaluationStats(supplierId);

            if (stats.getGroupCount() == 0) {
                log.info("【供应商评价】统计信息查询: 供应商ID={} 无评价记录", supplierId);
                return Result.OK("未查询到评价记录", stats);
            }

            log.info("【供应商评价】统计信息查询成功: 供应商ID={}, 组数={}, 平均评分={}, 完工率={}%, 达标率={}%",
                    supplierId, stats.getGroupCount(), stats.getAverageScore(), stats.getOnTimeRate(), stats.getQualityStandardRate());

            return Result.OK(stats);
        } catch (Exception e) {
            log.error("【供应商评价】统计信息查询失败: 供应商ID={}, 异常信息={}", supplierId, e.getMessage(), e);
            return Result.error("查询统计信息失败: " + e.getMessage());
        }
    }
}
